package cn.jsprun.filter;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.jsprun.utils.Common;
import cn.jsprun.utils.FileCaptureResponseWrapper;
import cn.jsprun.utils.ForumInit;
import cn.jsprun.utils.JspRunConfig;
public class FileCaptureFilter implements Filter {
	public void init(FilterConfig fc) throws ServletException {
	}
	public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = request.getSession();
		Integer uid = (Integer) session.getAttribute("jsprun_uid");
		if(uid!=null&&uid==0){
			String accessPath = request.getRequestURI();
			int index = accessPath.lastIndexOf("/");
			if(index != -1&&accessPath.indexOf("archiver")==-1&&accessPath.indexOf("wap")==-1){
				accessPath=accessPath.substring(index + 1);
			}
			HttpServletResponse response = (HttpServletResponse) res;
			Map<String,String> settings=ForumInit.settings;
			if(accessPath.equals("index.jsp")||accessPath.equals("")||accessPath.equals(settings.get("indexname"))){
				int cacheindexlife=Common.toDigit(settings.get("cacheindexlife"));
				String param = request.getQueryString();
				if(cacheindexlife>0&&param==null){
					String realPath=JspRunConfig.realPath;
					Object[] indexCache = Common.getCacheInfo("0",realPath+settings.get("cachethreaddir"));
					String fileName=(String)indexCache[1];
					File file = new File(fileName);
					if(file.exists()&&file.length()==0){
						file.delete();
						int timestamp = (Integer)(request.getAttribute("timestamp"));
						String timeoffset=(String)session.getAttribute("timeoffset");
						String debugtime =Common.gmdate("HH:mm:ss",timestamp,timeoffset);
						FileCaptureResponseWrapper responseWrapper = new FileCaptureResponseWrapper(response);  
						chain.doFilter(request, responseWrapper); 
						String content =null;
						if("1".equals(settings.get("debug"))){
							content = "<script type=\"text/javascript\">document.getElementById(\"debuginfo\").innerHTML = \"Update at "+debugtime+", Processed in 0.009121 second(s), 0 Queries\";</script>";
						}
						responseWrapper.writeFile(fileName,content);
						try {
							request.getRequestDispatcher(fileName.substring(realPath.length())).include(request, response);
						} catch (Exception e) {
						}
						return;
					}
				}
			}else if(accessPath.equals("viewthread.jsp")||accessPath.startsWith("thread-")){
				int cacheindexlife=Common.toDigit(settings.get("cacheindexlife"));
				if(cacheindexlife>0){
					String realPath=JspRunConfig.realPath;
					String tid = request.getParameter("tid");
					String page = request.getParameter("page");
					if(accessPath.startsWith("thread-")){
						tid = accessPath.replaceAll("thread-([0-9]+)-([0-9]+)-([0-9]+)\\.html", "$1");
						page = accessPath.replaceAll("thread-([0-9]+)-([0-9]+)-([0-9]+)\\.html", "$3");
					}
					page = page==null?"1":page;
					Object[]threadcache = Common.getCacheInfo(String.valueOf(Common.toDigit(tid)),realPath+settings.get("cachethreaddir"));
					String fileName=(String)threadcache[1];
					File file = new File(fileName);
					if(file.exists()&&file.length()==0&&page.equals("1")){
						file.delete();
						int timestamp = (Integer)(request.getAttribute("timestamp"));
						String timeoffset=(String)session.getAttribute("timeoffset");
						String debugtime =Common.gmdate("HH:mm:ss",timestamp,timeoffset);
						FileCaptureResponseWrapper responseWrapper = new FileCaptureResponseWrapper(response);  
						chain.doFilter(request, responseWrapper); 
						String content =null;
						if("1".equals(settings.get("debug"))){
							content = "<script type=\"text/javascript\">document.getElementById(\"debuginfo\").innerHTML = \"Update at "+debugtime+", Processed in 0.009121 second(s), 0 Queries\";</script>";
						}
						responseWrapper.writeFile(fileName,content);
						try {
							request.getRequestDispatcher(fileName.substring(realPath.length())).include(request, response);
						} catch (Exception e) {
						}
						return;
					}
				}
			}
		}
		chain.doFilter(req, res);
	}
	
	public void destroy() {
	}
}